package com.fingard.startup;


import com.fingard.FGBiz;
import com.fingard.dsp.bank.directbank.specialDeal.AutoQueryTrans;
import com.fingard.dsp.bankset.BankFront;
import com.fingard.dsp.tcpserver.RequestNIO;
import com.fingard.dsp.tcpserver.ServerSocketByThread;
import com.fingard.dsp.tcpserver.ThreadReceipt;
import com.fingard.dsp.web.HttpServer;
import com.fingard.text.StringHelper;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**启动DSP银行接口服务*/
public class BankServer {

    public HttpServer webServer = null;
    private ServerSocketByThread serverSocketThread;
    private Thread asyncThread;
    private ThreadReceipt threadReceipt;
    ScheduledExecutorService pool = null;
    
    public void addRequest(RequestNIO reqNIO) throws Exception{
    	if(serverSocketThread!=null){
    		serverSocketThread.addRequest(reqNIO);
    	}else{
    		FGBiz.limitMsg.error("BankServer.addRequest", "serverSocketThread为null");
    		reqNIO.reqSocketReceiver.clientSocketChannel.close();
    	}
    }
    
	public void start(boolean p_isAsync) throws Exception{
        if (FGBiz.dspCenter.dspSet.webPort > 0) {
            //com.sun.net.httpserver.HttpServer dd = new com.sun.net.httpserver.HttpServer();
        	if (!FGBiz.dspCenter.dspSet.disableWeb) {
	    		webServer = new HttpServer(FGBiz.dspCenter.dspSet.webPort);
	            webServer.start();
	            FGBiz.startLog.addLogNoTime("DSP Web地址：http://" + FGBiz.localHostIp + ":" + FGBiz.dspCenter.dspSet.webPort);
	            FGBiz.startLog.addLogNoTime("DSP Web主目录：" + FGBiz.dspCenter.dspSet.webDirPath);
        	}
        }

        if ("true".equals(FGBiz.dspCenter.dspSet.disableTaskTimer)
                && FGBiz.dspCenter.dspSet.taskIntervalSecs>0) {
            pool = Executors.newScheduledThreadPool(1);
            threadReceipt=new ThreadReceipt(new BankFront());
            pool.scheduleWithFixedDelay(threadReceipt,0,FGBiz.dspCenter.dspSet.taskIntervalSecs,TimeUnit.SECONDS);
            FGBiz.startLog.addLogNoTime("DSP 回单定时上传推送任务启动，轮询间隔时间："+FGBiz.dspCenter.dspSet.taskIntervalSecs+"秒");
        }
        
        
            //快钱反馈是由于他们的JDK版本是1.6，如果采用的JDK版本是1.7，需要在代码中设置系统属性：
            System.setProperty("jsse.enableSNIExHttpClienttension", "false");
            FGBiz.startLog.addLogNoTime("jsse.enableSNIExHttpClienttension：false");
            FGBiz.startLog.addLogNoTime("本次程序启动为：" + (FGBiz.dspCenter.dspSet.useDBConn ? "数据库版" : "文件版"));

            if (!FGBiz.dspCenter.dspSet.useDBConn) {
                if (FGBiz.dspCenter.dspSet.enableBankPayInfo) {
                    throw new Exception("未启用数据库版，不能使用支付信息表配置，请修改");
                }
                if (FGBiz.dspCenter.enableAutoTodayTrans) {
                    throw new Exception("未启用数据库版，不能使用自动当日明细查询配置，请修改");
                }
                if (FGBiz.dspCenter.enableAutoHisTrans) {
                    throw new Exception("未启用数据库版，不能使用自动历史明细查询配置，请修改");
                }
                if (FGBiz.dspCenter.convertBankArea) {
                    throw new Exception("未启用数据库版，不能使用转换银行区域信息配置，请修改");
                }
                if (FGBiz.dspCenter.convertPayState) {
                    throw new Exception("未启用数据库版，不能使用转换收付状态信息配置，请修改");
                }
                if (FGBiz.dspCenter.enableCacheCurTrans) {
                    throw new Exception("未启用数据库版，不能使用缓存当日明细数据配置，请修改");
                }
                if (FGBiz.dspCenter.enableCacheHisTrans) {
                    throw new Exception("未启用数据库版，不能使用缓存历史明细数据配置，请修改");
                }
            }


            FGBiz.startLog.addLogNoTime("数据文件主目录：" + FGBiz.dspCenter.dspSet.dataDirPath);
            FGBiz.startLog.addLogNoTime("日志默认主目录：" + FGBiz.dspCenter.dspSet.logsMainDir);
            FGBiz.startLog.addLogNoTime("直联日志主目录：" + FGBiz.dspCenter.dspSet.bankLogsDirPath);
            FGBiz.startLog.addLogNoTime("BankLogs日志一级目录：" + FGBiz.dspCenter.dspSet.bankLogsFirstDir);
            FGBiz.startLog.addLogNoTime("直联日志格式：" + FGBiz.dspCenter.dspSet.bankLogsFormat);
            FGBiz.startLog.addLogNoTime("直联日志启用异步日志模式：" + FGBiz.dspCenter.dspSet.enableAsyncBankLog);

            if (FGBiz.dspCenter.dspSet.enableDbLog && FGBiz.dspCenter.dspSet.dbConnectionSet != null) {
            	FGBiz.startLog.addLogNoTime("数据库日志已开启");
            	FGBiz.startLog.addLogNoTime("useJndi：" + FGBiz.dspCenter.dspSet.dbConnectionSet.useJndi);
                if (StringHelper.hasAnyChar(FGBiz.dspCenter.dspSet.dbConnectionSet.useJndiFactory)) {
                	FGBiz.startLog.addLogNoTime("useJndiFactory：" + FGBiz.dspCenter.dspSet.dbConnectionSet.useJndiFactory);
                }
            }
            
            try {
                FGBiz.dspCenter.startListener();
                FGBiz.dspCenter.startScheduleTask();
            } catch (Throwable t) {
            	FGBiz.startLog.exception("BankServer.start", t);
            }

            String useSimaulateBankCode = "";
            if (StringHelper.isNullOrEmpty(FGBiz.dspCenter.dspSet.enableSimulate) || "false".equalsIgnoreCase(FGBiz.dspCenter.dspSet.enableSimulate)) {
                useSimaulateBankCode = "无";
            } else if ("true".equalsIgnoreCase(FGBiz.dspCenter.dspSet.enableSimulate)) {
                useSimaulateBankCode = "全渠道";
            } else {
                useSimaulateBankCode = StringHelper.trimEnd(StringHelper.trimStart(FGBiz.dspCenter.dspSet.enableSimulate, ","), ",").trim();
            }
            FGBiz.startLog.addLogNoTime("当前启用前置挡板的渠道：" + useSimaulateBankCode);

            String useBankSimaulateBankCode = "";
            if (StringHelper.isNullOrEmpty(FGBiz.dspCenter.dspSet.bankSimulate) || "false".equalsIgnoreCase(FGBiz.dspCenter.dspSet.bankSimulate)) {
                useBankSimaulateBankCode = "无";
            } else if ("true".equalsIgnoreCase(FGBiz.dspCenter.dspSet.bankSimulate)) {
                useBankSimaulateBankCode = "全渠道";
            } else {
                useBankSimaulateBankCode = StringHelper.trimEnd(StringHelper.trimStart(FGBiz.dspCenter.dspSet.bankSimulate, ","), ",").trim();
            }
            FGBiz.startLog.addLogNoTime("当前启用后置挡板的渠道：" + useBankSimaulateBankCode);
            
            if(StringHelper.hasAnyChar(FGBiz.dspCenter.dspSet.masterServer)){
            	FGBiz.startLog.addLogNoTime("主控服务器地址：" + FGBiz.dspCenter.dspSet.masterServer);
            }

            AutoQueryTrans.run();

            if(FGBiz.dspCenter.dspSet.listenerPort > 0){
            	FGBiz.startLog.addToLimit("BankServer", "开启直联接口服务，侦听端口：" + FGBiz.dspCenter.dspSet.listenerPort);
                
                serverSocketThread = new ServerSocketByThread(FGBiz.dspCenter.dspSet.listenerPort);
                if (p_isAsync) {
                    asyncThread = new Thread(serverSocketThread);
                    asyncThread.start();
                } else {
                    serverSocketThread.start();
                }
            }else{
            	FGBiz.startLog.addToLimit("BankServer", "未配置有效Socket侦听端口（值为"+FGBiz.dspCenter.dspSet.listenerPort+"），不开启Socket服务侦听");
            }

	}
	
    public String stopDirect() {
    	FGBiz.startLog.addToLimit("BankServer.stop", "停止DSP侦听服务");
    	String stop1="";
        if (serverSocketThread != null) {
        	stop1 = serverSocketThread.stop();
        }
        String stop2 = FGBiz.dspCenter.stopListener();
        String stop3 = FGBiz.dspCenter.stopScheduleTask();
        return StringHelper.joinNotEmpty("\r\n", stop1,stop2,stop3);
    }
    
    public String stopWeb() {
    	StringBuilder sbMsg = new StringBuilder();
    	if(webServer != null){
    		webServer.stop();
    	}
    	return sbMsg.toString();
    }
}
